package edu.ccut.saturn.manager.menu.core;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IMuneItemInfo;
import edu.ccut.saturn.component.IParameterContext;

public class UpdateDataForMenuItemMove extends DefaultComponent {
	
	private static final String ORDER_QUERY_SQL = "SELECT value FROM saturnconfig WHERE id = ? and type = 'menu' and symbolicName = ?";
	private static final String ORDER_UPDATE_SQL = "update saturnconfig set value = ? WHERE id = ? and type = 'menu' and symbolicName = ?";
	private static final String ORDER_INSERT_SQL = "insert into saturnconfig (id,type,symbolicName,value) values (?,'menu',?,?)";

	@Override
	public void execute(IParameterContext parameterContext) throws Exception {

		IMuneItemInfo menuItem = (IMuneItemInfo) parameterContext
				.getParameterValue(0);

		String id = menuItem.getId();
		String bundleName = menuItem.getMenuInfo().getBundleSymbolicName();
		String order = menuItem.getOrder();

		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			preparedStatement = parameterContext.getConnection()
					.prepareStatement(ORDER_QUERY_SQL);

			preparedStatement.setString(1, id);
			preparedStatement.setString(2, bundleName);
			resultSet = preparedStatement.executeQuery();
			if (!resultSet.next()) {
				preparedStatement = parameterContext.getConnection()
						.prepareStatement(ORDER_INSERT_SQL);

				preparedStatement.setString(1, id);
				preparedStatement.setString(2, bundleName);
				preparedStatement.setString(3, order);
				preparedStatement.executeUpdate();

			} else if (!order.equals(resultSet.getString("value"))) {
				preparedStatement = parameterContext.getConnection()
						.prepareStatement(ORDER_UPDATE_SQL);

				preparedStatement.setString(1, order);
				preparedStatement.setString(2, id);
				preparedStatement.setString(3, bundleName);
				preparedStatement.executeUpdate();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (preparedStatement != null) {
				preparedStatement.close();
			}
			if (resultSet != null) {
				resultSet.close();
			}
		}
	}
}